package com.dylovedz.javafxphone.service;

import cn.hutool.core.bean.BeanUtil;
import com.aspose.words.DocumentBuilder;
import com.aspose.words.SaveFormat;
import com.dylovedz.javafxphone.controller.vo.WechatExcelVO;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNewsBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpNewsArticle;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Component
public class WechatService {

    public void saveHtml2Word(String path, WechatExcelVO article) throws Exception {

        //导出源内容
        /*String textFileName = path +  File.separator + index + ".txt";
        BufferedOutputStream textOutputStream = FileUtil.getOutputStream(textFileName);
        IoUtil.write(textOutputStream, true, article.getContent().getBytes(StandardCharsets.UTF_8));*/

        // 设置图片地址
        Document document = Jsoup.parse(article.getContent());
        Elements imgs = document.getElementsByTag("img");
        for (Element img : imgs) {
            img.attr("src", img.attr("data-src"));
        }
        article.setContent(document.html() + "<style> img {max-width: 100%}</style>");

        // 导出html
        /*String fileName = path +  File.separator + index + ".html";
        BufferedOutputStream outputStream = FileUtil.getOutputStream(fileName);
        IoUtil.write(outputStream, true, article.getContent().getBytes(StandardCharsets.UTF_8));*/

        // 导出world
        com.aspose.words.Document doc = new com.aspose.words.Document();
        DocumentBuilder documentBuilder = new DocumentBuilder(doc);
        documentBuilder.insertHtml(article.getContent());
        String order = article.getOrder() > 0 ? "_" + article.getOrder() : "";
        String worldFileName = path +  File.separator + article.getOffset() + order + ".docx";
        doc.save(worldFileName, SaveFormat.DOCX);
    }

    public int getTotalPage(WxMpServiceImpl wxMpService, int pageSize) throws WxErrorException {
        WxMpMaterialNewsBatchGetResult wxMpMaterialNewsBatchGetResult = wxMpService.getMaterialService().materialNewsBatchGet(0, 1);
        return wxMpMaterialNewsBatchGetResult.getTotalCount() / pageSize;
    }

    public List<WechatExcelVO> getPageResult(WechatService wechatService, WxMpServiceImpl wxMpService, int start, int end, String outDir, MaterialTask materialTask) {
        if (materialTask.isCancelled()) {
            return null;
        }
        List<WechatExcelVO> wechatExcelList = new ArrayList<>();
             /*WxMpFreePublishList publicationRecords = wxMpService.getFreePublishService().getPublicationRecords(offset, 20);
                int publishCount = publicationRecords.getTotalCount();
                for (WxMpFreePublishItem item : publicationRecords.getItems()) {
                    for (WxMpFreePublishArticles article : item.getContent().getNewsItem()) {
                        WechatExcelVO articleItem = new WechatExcelVO();
                        BeanUtil.copyProperties(article, articleItem);
                        wechatExcelList.add(articleItem);
                        wechatService.saveHtml2Word(outDir, articleItem, totalPublish);
                        totalPublish += 1;
                    }
                }*/
        for (int i = start; i<= end; i++) {
            try {
                int offset = i * 20;
                WxMpMaterialNewsBatchGetResult wxMpMaterialNewsBatchGetResult = wxMpService.getMaterialService().materialNewsBatchGet(offset, 20);
                int newsCount = wxMpMaterialNewsBatchGetResult.getTotalCount();
                int itemIndex = 0;
                for (WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem item : wxMpMaterialNewsBatchGetResult.getItems()) {
                    int orderIndex = 0;
                    for (WxMpNewsArticle article : item.getContent().getArticles()) {
                        WechatExcelVO articleItem = new WechatExcelVO();
                        BeanUtil.copyProperties(article, articleItem);
                        articleItem.setOffset(offset + itemIndex);
                        articleItem.setOrder(orderIndex);
                        wechatExcelList.add(articleItem);
                        try {
                            if (materialTask.isCancelled()) {
                                break;
                            }
                            wechatService.saveHtml2Word(outDir, articleItem);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        orderIndex++;
                        MaterialRunTask.addNum();
                    }
                    itemIndex++;
                }
                System.out.println(newsCount);
            } catch (WxErrorException e) {
                e.printStackTrace();
            }
        }
        return wechatExcelList;
    }
}
